package handlers

import (
	"data-stat-mgr/cache"
	"data-stat-mgr/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))

	offset := (page - 1) * size

	var count int64
	models.DB.Model(&models.Rest{}).Count(&count)

	var rest []models.Rest

	redis_key := "list_rest" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&rest)
		jsonData, _ := json.Marshal(rest)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &rest)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"rest":  rest,
		},
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var rest models.Rest

	redis_key := "detail_rest" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id = ?", id).First(&rest)
		jsonData, _ := json.Marshal(rest)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": rest,
	})
	return
}
func Collection(c *gin.Context) {
	userId, _ := strconv.Atoi(c.Query("user_id"))
	restId, _ := strconv.Atoi(c.Query("rest_id"))

	var collection models.Collection
	err := models.DB.Where("user_id = ? && rest_id = ?", userId, restId).First(&collection).Error
	if err == nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能重复收藏",
		})
		return
	}

	collection = models.Collection{
		UserID: userId,
		RestID: restId,
	}
	err = models.DB.Create(&collection).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加收藏失败",
		})
		return
	}

	var rest models.Rest
	err = models.DB.Where("id = ?", restId).First(&rest).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不存在",
		})
		return
	}

	rest.CollectionCount++
	err = models.DB.Save(&rest).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "收藏失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "收藏成功",
	})
	return
}
